from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from QQLoginTool.QQtool import OAuthQQ
from rest_framework import status
import logging
from rest_framework_jwt.settings import api_settings

from django.conf import settings
from .models import QQAuthUser
from .utils import generate_save_user_token
from .serializers import QQAuthUserSerializer

logger = logging.getLogger('django')


# Create your views here.
# QQ登录参数配置
# QQ_CLIENT_ID = '101514053'
# QQ_CLIENT_SECRET = '1075e75648566262ea35afa688073012'
# QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'
class QQAuthUserView(APIView):
    """扫码成功后回调处理"""

    def get(self, request):
        # 1.获取参数 code
        code = request.query_params.get("code")
        # 1.1 对code进行校验
        if not code:
            return Response({"message": "缺少code"}, status=status.HTTP_400_BAD_REQUEST)

        # 2.创建qq登录对象
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
        )
        try:
            # 2.1 获取open_id值
            access_token = qq.get_access_token(code)
            # 2.1 获取access_token值
            openid = qq.get_open_id(access_token)
        except Exception as result:
            logger.info(result)
            # HTTP_503_SERVICE_UNAVAILABLE 服务不可获取
            return Response({"message": "QQ服务器异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 通过openid查询数据库,判断用户是不是第一次登录
        try:
            qq_user = QQAuthUser.objects.get(openid=openid)
        except QQAuthUser.DoesNotExist:

            # 如果没有查询到,将数据进行加密返回给前段进行保存
            token = generate_save_user_token(openid)
            print(token)

            return Response({'access_token': token})
        else:
            # 如果openid存在,说明用户不是第一次登陆,表名用户已经是注册用户
            user = qq_user.user
            # 手动生成状态保持
            # 补充生成记录登录状态的token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 载荷
            payload = jwt_payload_handler(user)
            # 签证
            token = jwt_encode_handler(payload)
            # 组织数据返回
            data = {
                "token": token,
                "username": user.username,
                "user_id": user.id
            }
            return Response(data=data)

    def post(self, request):
        """对用户信息进行绑定"""
        # 1.获取参数 mobile 手机号 , 验证码sms_code , 密码password , 加密后的openid (access_token)

        # 创建序列化器对象,进行反序列化
        serializer = QQAuthUserSerializer(data=request.data)
        print(request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 手动生成jwt Token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载生成载荷函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token函数
        # 获取user对象

        payload = jwt_payload_handler(user)  # 生成载荷
        token = jwt_encode_handler(payload)  # 根据载荷生成token
        # 组织数据返回
        data = {
            "token": token,
            "username": user.username,
            "user_id": user.id
        }
        print(data)
        return Response(data=data)


class QQAuthUrlView(APIView):
    """返回qq扫码链接视图"""

    def get(self, request):
        # 1.获取参数 next
        next = request.query_params.get("next")
        if not next:
            return '/'
        # 2.创建qq登录对象
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )
        # 3.调用方法获取QQ登录url
        login_url = qq.get_qq_url()

        return Response({"login_url": login_url})
